#include "../include/log4cppuse.h"

#include <iostream>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Category.hh>
#include<log4cpp/RollingFileAppender.hh>
using namespace std;
using namespace log4cpp;



Logger * Logger::getInstance()
{
    if(_pInstance==nullptr)
    {
        _pInstance=new Logger();
    }
    return _pInstance;
}

void Logger::destroy()
{
    delete _pInstance;
}



Logger::Logger()
{
    //1.1.创建控制台解释器
    OstreamAppender *appender1=new OstreamAppender("con",&cout);
    //1.2创建文件解释器
    RollingFileAppender * appender2=new RollingFileAppender("roll","log.txt",1024*1024*2,4);
    
    //2.1创建控制台的布局
    PatternLayout *layout1=new PatternLayout();

    //2.2创建文件的布局
    PatternLayout *layout2=new PatternLayout();

    //diy格式
    layout1->setConversionPattern("%d [%p] %m%n");
    layout2->setConversionPattern("%d [%p] %m%n");
    
    //3.进行解释器与格式的绑定
    appender1->setLayout(layout1);
    appender2->setLayout(layout2);

    //4.添加根记录器
    _root=&Category::getRoot();
    _root->addAppender(appender1);
    _root->addAppender(appender2);

    //5.进行创建优先级
    _root->setPriority(Priority::DEBUG);
}



Logger::~Logger()
{
    Category::shutdown();
}


void Logger::warn(const char * file, int line, const char * func, const char * msg)
{
    std::lock_guard<std::mutex>lock(mutex_);
    char buf[1024];
    snprintf(buf,1024,"[%s: %s :%d] %s",file,func,line ,msg);
    _root->warn("%s",buf);
}
void Logger::error(const char * file, int line, const char * func, const char * msg)
{
    std::lock_guard<std::mutex>lock(mutex_);
    char buf[1024];
    snprintf(buf,1024,"[%s: %s :%d] %s",file,func,line ,msg);
    _root->error("%s",buf);
}
void Logger::debug(const char * file, int line, const char * func, const char * msg)
{
    std::lock_guard<std::mutex>lock(mutex_);
    char buf[1024];
    snprintf(buf,1024,"[%s: %s :%d] %s",file,func,line ,msg);
    _root->debug("%s",buf);
}
void Logger::info(const char * file, int line, const char * func, const char * msg)
{
    std::lock_guard<std::mutex>lock(mutex_);
    char buf[1024];
    snprintf(buf,1024,"[%s: %s :%d] %s",file,func,line ,msg);
    _root->info("%s",buf);
}



Logger * Logger::_pInstance=nullptr;
Category *Logger:: _root=nullptr;


#if 0

int main() {
    LOG_INFO("测试 INFO 日志");
    LOG_ERROR("测试 ERROR 日志");
    LOG_DEBUG("测试 DEBUG 日志");
    LOG_WARN("测试WARN  日志");
    return 0;
}
#endif
